package com.zh.kotlin_mvvm.provider

import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri

/**
 * 参照链接：
 * 1、https://www.jianshu.com/p/80b8abfdd531
 * 2、https://blog.csdn.net/M_Nobody/article/details/126100662
 */
class MyContentProvider : ContentProvider() {

    private var dbHelper: SQLiteDatabase? = null

    override fun onCreate(): Boolean {
        dbHelper = MyDatabaseHelper(context).writableDatabase
        return dbHelper != null
    }

    override fun query(
        uri: Uri, projection: Array<String>?, selection: String?,
        selectionArgs: Array<String>?, sortOrder: String?
    ): Cursor? {
        return try {
            dbHelper?.let {
                return it.query(
                    AdProviderUtils.instance.queryTable,
                    projection, selection, selectionArgs, null, null, sortOrder
                )
            }
        } catch (e: Throwable) {
            e.printStackTrace()
            null
        }
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        return try {
            dbHelper?.let {
                val newBookId = it.insert(AdProviderUtils.instance.queryTable, null, values)
                Uri.parse("$uri/$newBookId")
            }
        } catch (e: Throwable) {
            e.printStackTrace()
            null
        }
    }

    override fun update(
        uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?
    ): Int {
        return try {
            dbHelper?.update(AdProviderUtils.instance.queryTable, values, selection, selectionArgs)
                ?: 0
        } catch (e: Throwable) {
            e.printStackTrace()
            0
        }
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
        return try {
            dbHelper?.delete(AdProviderUtils.instance.queryTable, selection, selectionArgs) ?: 0
        } catch (e: Throwable) {
            e.printStackTrace()
            0
        }
    }

    override fun getType(uri: Uri) = null
}